import React from 'react'
import { connect } from 'react-redux'
import { messages, getDefaultSetOfBook } from "share/common"
import menuRoute from 'routes/menuRoute'
import { Form, Card, Spin, Icon, Row, Col, Modal, message, Radio, Button } from 'antd'
import creditImg from 'images/setting/workflow/credit.svg'
const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;

import manApprovalImg from 'images/setting/workflow/man-approval.svg'
import knowImg from 'images/setting/workflow/know.svg'
import aiApprovalImg from 'images/setting/workflow/aiapproval.svg'
import mailImg from 'images/setting/workflow/mail.png'
import auditImg from 'images/setting/workflow/audit.png'
import endImg from 'images/setting/workflow/end.png'
import noFormImg from 'images/setting/workflow/no-form.png'
import configureStore from "stores";
import { setDefaultSetOfBook } from "actions/cache";
import Selector from 'components/selector'
import workflowService from 'containers/setting/workflow/workflow.service'
import 'styles/setting/workflow/workflow.scss'
import Condition from 'components/condition'
const { If } = Condition;
import NewWorkflowDetail from 'containers/setting/new-workflow/detail/workflow-detail'

class Workflow extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      pasteLoading: false, //粘贴后页面loading
      data: [],
      setOfBooksId: props.location.query.setOfBooksId || props.company.setOfBooksId,
      setOfBooksName: props.location.query.setOfBooksName || props.company.setOfBooksName,
      sourceFormOID: null, //复制的表单OID
      workflowDetail: menuRoute.getRouteItem('workflow-setting', 'key'), //审批流设置
      showEnableList: true, //显示启用的单据
      newWorkflowVisible: false,
    }
  }

  componentDidMount() {
    const { tenantMode } = this.props;
    if (sessionStorage.getItem('sourceFormOIDData') && sessionStorage.getItem('sourceFormOIDData') !== 'null') {
      let sourceFormOIDData = JSON.parse(sessionStorage.getItem('sourceFormOIDData'));
      if ((new Date().getTime() - sourceFormOIDData.timestamp) / 3600000 < 24) {
        this.setState({
          sourceFormOID: sourceFormOIDData.sourceFormOID
        })
      }
    }
    if (tenantMode) {
      getDefaultSetOfBook().then(resp => {
        if (resp.data) {
          this.setState({
            setOfBooksId: resp.data.defaultSetOfBooksId,
            setOfBooksName: resp.data.defaultSetOfBooksName
          }, () => {
            this.getList();
          });
        }
      }).catch(error => {
        message.error(messages('common.error'));
      });
    } else {
      this.getList();
    }
  }

  getList = () => {
    this.setState({ loading: true });
    workflowService.getWorkflowList(this.props.tenantMode ? this.state.setOfBooksId : '').then(res => {
      this.setState({
        loading: false,
        data: res.data
      })
    })
  };

  //集团模式下改变帐套
  handleSetOfBooksChange = (value) => {
    value && this.setState({
      setOfBooksId: value.id,
      setOfBooksName: value.setOfBooksName,
      showEnableList: true
    },() => {
      configureStore.store.dispatch(setDefaultSetOfBook({
        setOfBooksId: value.id,
        setOfBooksName: value.setOfBooksName,
      }));
      this.getList()
    })
  };

  //获取节点图片
  getNodeImg = (type) => {
    switch(type) {
      case 1001:  //审批
        return <img src={manApprovalImg} className="node-image"/>;
      case 1002:  //知会
        return <img src={knowImg} className="node-image"/>;
      case 1003:  //机器人
        return <img src={aiApprovalImg} className="node-image"/>;
      case 1004:  //发送打印
        return <img src={mailImg} className="node-image"/>;
      case 1006:  //审核
        return <img src={auditImg} className="node-image"/>;
      case 1005:  //结束
        return <img src={endImg} className="node-image"/>;
      case 1007:  //信用审批
        return <img src={creditImg} className="node-image"/>
    }
  };

  //复制审批链
  setFormCopyOID = (formOID) => {
    this.setState({ sourceFormOID: formOID }, () => {
      //localStorage.setItem('sourceFormOID', formOID);
      sessionStorage.setItem('sourceFormOIDData', JSON.stringify({
        sourceFormOID: formOID,
        timestamp: new Date().getTime()
      }));
    })
  }

  //显示粘贴确认框
  showConfirmModal = (targetFormOID) => {
    Modal.confirm({
      title: messages('setting.key1426'/*是否确认更改*/), //是否确认更改
      content: messages('setting.key1427'/*粘贴后将覆盖原审批流*/), //粘贴后将覆盖原审批流
      onOk: () => this.handleFormCopy(targetFormOID)
    })
  };

  //粘贴审批链
  handleFormCopy = (targetFormOID) => {
    this.setState({ pasteLoading: true });
    workflowService.copyApproveChains(this.state.sourceFormOID, targetFormOID).then(() => {
      workflowService.getWorkflowList(this.props.tenantMode ? this.state.setOfBooksId : '').then(res => {
        this.setState({
          pasteLoading: false,
          data: res.data
        });
      });
      message.success(messages('common.operate.success'))
    }).catch((err) => {
      this.setState({ loading: false })
      if (err.response && err.response.data) {
        message.error(err.response.data.message);
      }
    })
  };

  //显示新版审批流
  handleChangeVisible = (visible) => {
    console.log(visible)
    this.setState({ newWorkflowVisible:visible });
  };

  //进入详情页
  goDetail = (record) => {
    let url = this.state.workflowDetail.url.replace(':formOID', record.formOID);
    url += this.props.tenantMode ? `?setOfBooksId=${this.state.setOfBooksId}&setOfBooksName=${this.state.setOfBooksName}` : '';
    this.context.router.push(url)
  };

  render() {
    const { tenantMode, language } = this.props;
    const { loading, data, setOfBooksName, setOfBooksId, sourceFormOID, showEnableList, pasteLoading, newWorkflowVisible } = this.state;
    let enabledData = [];
    let disabledData = [];
    data.map(item => {
      item.valid ? enabledData.push(item) : disabledData.push(item)
    });
    return (
      <div className='workflow'>
        {tenantMode && (
          <div className="setOfBooks-container">
            <Row className="setOfBooks-select">
              <Col span={language.code === 'zh_cn' ? 4 : 8} className="title">{messages('setting.key1428'/*帐套*/)}：</Col>
              <Col span={16}>
                {!loading&&
                <Selector type="setOfBooksByTenant"
                          allowClear={false}
                          entity
                          value={{label: setOfBooksName, key: setOfBooksId}}
                          onChange={this.handleSetOfBooksChange}
                />}
              </Col>
            </Row>
          </div>
        )}
        {loading ? <Spin/> : (
          <Spin spinning={pasteLoading}>
            <div>
              <RadioGroup defaultValue={true} onChange={e => this.setState({showEnableList: e.target.value})}>
                <RadioButton value={true}>{messages('common.enabled')}</RadioButton>
                <RadioButton value={false}>{messages('common.disabled')}</RadioButton>
              </RadioGroup>
              {(showEnableList ? enabledData : disabledData).map(item => {
                return (
                  <Card key={item.formOID} className="card-list" type="inner"
                        title={(
                          <div>
                            <span>{item.formName}</span>
                            {showEnableList && (
                              <div className="card-title-extra">
                                <span className="ant-divider"/>
                                <a onClick={() => {this.goDetail(item)}}>{messages('setting.key1429'/*查看编辑*/)}</a>
                                {/*审批流复制粘贴功能只适用于自定义审批模式 bug 21262*/}
                                {item.ruleApprovalChain && item.ruleApprovalChain.approvalMode === 1005 && item.formType !== 8001 && (
                                  <div style={{display: 'inline-block'}}>
                                    <span className="ant-divider"/>
                                    <a onClick={() => {this.setFormCopyOID(item.formOID)}}>{messages('setting.key1430'/*复制*/)}</a>
                                    {sourceFormOID && <span className="ant-divider"/>}
                                    {sourceFormOID && <a onClick={() => {this.showConfirmModal(item.formOID)}}>{messages('setting.key1431'/*粘贴*/)}</a>}
                                  </div>
                                )}
                              </div>
                            )}
                          </div>
                        )}
                  >
                    <Row type="flex">
                      {item.ruleApprovalChain && item.ruleApprovalChain.approvalMode === 1005 &&
                      (item.ruleApprovalChain.ruleApprovalNodes || []).map((node, index) => {
                        return (
                          <div key={node.ruleApprovalNodeOID} className="node-container">
                            <div>
                              {this.getNodeImg(node.type)}
                              {index < item.ruleApprovalChain.ruleApprovalNodes.length - 1 && <Icon type="arrow-right" className="right-arrow"/>}
                            </div>
                            <p className="node-remark">{node.type === 1005 ? messages('setting.key1252'/*结束*/) : node.remark}</p>
                          </div>
                        )
                      })}
                      {item.ruleApprovalChain && item.ruleApprovalChain.approvalMode !== 1005 && (
                        <div className="node-container">
                          <div className="approval-block">{messages('setting.key1419'/*审*/)}</div>
                          <p className="node-remark">
                            {item.ruleApprovalChain.approvalMode === 1002 && messages('setting.key1413'/*部门经理*/)}
                            {item.ruleApprovalChain.approvalMode === 1003 && messages('setting.key1420'/*选人审批*/)}
                            {item.ruleApprovalChain.approvalMode === 1006 && messages('setting.key1421'/*英孚审批*/)}
                          </p>
                        </div>
                      )}
                    </Row>
                  </Card>
                )
              })}
              {showEnableList && !enabledData.length && (
                <div className="no-form-container">
                  <img src={noFormImg}/>
                  <p>{messages('setting.key1432'/*无【已启用】单据，请先前往 表单设计器 启用表单*/)}</p>
                </div>
              )}
            </div>
          </Spin>
        )}
      </div>
    )
  }
}

Workflow.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    tenantMode: state.main.tenantMode,
    company: state.login.company,
    language: state.main.language,
  }
}

const wrappedWorkflow = Form.create()(Workflow);

export default connect(mapStateToProps)(wrappedWorkflow)
